// 病床管理
import { useState, useEffect } from "react";
import {
  Space,
  Table,
  Pagination,
  Input,
  Button,
  Modal,
  Form,
  Radio,
  Select,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  Bedintegratedmanagement,
  Bedremoval,
  Batchremovalofbeds,
  Bedmodification,
  Medicaldepartment,
} from "../../../request/zwyApi";
import "../../../assets/zwyAssets/zwyiconfont/iconfont.css";
import modulesCss from "../../../styles/BedList.module.css";

const { Column } = Table;

function BedList() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectIds, setIds] = useState([]); // 选中的表格行id
  const [bedNumber, setBedNumber] = useState(""); // 存储输入框的值
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [idToDelete, setIdToDelete] = useState(null); // 存储要删除的 id

  const [editingRecord, setEditingRecord] = useState(null);
  const [isManageModalOpen, setIsManageModalOpen] = useState(false);

  const [departments, setDepartments] = useState([]); // 存储科室数据
  const [nurses, setNurses] = useState([]); // 存储护士数据

  const [form] = Form.useForm();

  useEffect(() => {
    fetchData();
    fetchMedicalData(); // 新增函数调用
  }, [currentPage, pageSize]);

  const fetchData = async (bedNumber = "", page) => {
    setLoading(true);
    try {
      const res = await Bedintegratedmanagement({
        page: page !== undefined ? page : currentPage,
        size: pageSize,
        bednumber: bedNumber,
      });
      console.log(res);
      setData(res.data);
      setTotal(res.total);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  // 新增函数来获取医生和科室数据
  const fetchMedicalData = async () => {
    try {
      const res = await Medicaldepartment({ page: 1, size: 100 });
      setDepartments(
        res.data.map((item) => ({ value: item.name, label: item.name }))
      );
      setNurses(
        res.data.map((item) => ({
          value: item.maindoctor,
          label: item.maindoctor,
        }))
      );
    } catch (error) {
      console.error("Error fetching medical data:", error);
    }
  };

  const onChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
    setIds([]); // 切换页码时清空选中状态
  };

  // 复选框操作
  const rowSelection = {
    type: "checkbox",
    selectedRowKeys: selectIds,
    onChange: (selectedRowKeys) => {
      setIds(selectedRowKeys);
    },
  };

  const renderIcon = (value) => {
    return value === 1 ? (
      <span style={{ color: "green" }}>√</span>
    ) : (
      <span style={{ color: "red" }}>×</span>
    );
  };

  // 输入框的 onChange 事件处理函数
  const handleInputChange = (e) => {
    setBedNumber(e.target.value);
  };

  // 查询按钮的 onClick 事件处理函数
  const handleSearch = () => {
    setCurrentPage(1); // 更新 currentPage 状态为 1
    fetchData(bedNumber, 1); // 明确传递 page 参数为 1
  };

  // 删除按钮的点击事件处理函数
  const handleDelete = (id) => {
    showModal();
    setIdToDelete(id);
  };

  const handleEdit = (record) => {
    // 将当前行的数据设置为表单的初始值
    console.log(record);

    setEditingRecord(record);
    setIsManageModalOpen(true);
    form.setFieldsValue({
      bednumber: record.bednumber,
      department: record.department,
      oxygen: record.oxygen,
      heart: record.heart,
      nurse: record.nurse,
      breath: record.breath,
      icu: record.icu,
      aircondition: record.aircondition,
      tv: record.tv,
    });
  };

  const handleManageOk = async () => {
    form.validateFields().then(async (values) => {
      const updatedRecord = {
        ...editingRecord,
        ...values,
      };
      const res = await Bedmodification(updatedRecord);
      if (res && res.code === 1) {
        message.success("编辑成功");
      } else {
        message.error("编辑失败");
      }
      setIsManageModalOpen(false); // 在验证成功后关闭模态框
      fetchData(); // 更新数据后重新获取数据以更新表格
    });
  };

  const handleManageCancel = () => {
    setEditingRecord(null);
    setIsManageModalOpen(false);
  };

  // 删除选中按钮的点击事件处理函数
  const handleBatchDelete = () => {
    if (selectIds.length === 0) {
      message.warning("请先选中要删除的床位。");
      return;
    }
    const idsString = selectIds.join(","); // 将数组转换为字符串
    console.log(idsString); // 打印转换后的字符串
    showModal();
  };

  // Modal 的 onOk 事件处理函数
  const handleOk = async () => {
    try {
      if (idToDelete) {
        await Bedremoval({ id: idToDelete });
        message.success("删除成功");
      } else {
        await Batchremovalofbeds({ ids: JSON.stringify(selectIds) }); // 将数组转换为字符串

        message.success("选中的床位删除成功。");
        setIds([]); // 清空选中状态
      }
      fetchData(); // 删除后重新获取数据以更新表格
    } catch (error) {
      message.error("床位删除失败，请稍后再试。");
    } finally {
      setIsModalOpen(false);
    }
  };

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div className={modulesCss.box}>
      <Space className={modulesCss.spacebox}>
        <span style={{ fontWeight: "600" }}>床位编号</span>
        <Input
          placeholder="请输入床位编号进行查询"
          style={{ width: "250px" }}
          onChange={handleInputChange}
          allowClear
        />
        <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
          查询
        </Button>
        <Button
          color="default"
          variant="outlined"
          onClick={handleBatchDelete}
          className={modulesCss.delbut}
        >
          删除选中
        </Button>
      </Space>

      <Table
        rowKey={(record) => record.id}
        rowSelection={rowSelection}
        loading={loading}
        dataSource={data}
        pagination={false}
        className={modulesCss.tablebox}
      >
        <Column title="床位编号" dataIndex="bednumber" key="bednumber" />
        <Column title="所属科室" dataIndex="department" key="department" />
        <Column title="责任护士" dataIndex="nurse" key="nurse" />
        <Column
          title="配备氧气罐"
          dataIndex="oxygen"
          key="oxygen"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="配备心电机"
          dataIndex="heart"
          key="heart"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="配备呼吸机"
          dataIndex="breath"
          key="breath"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="配备急救设备"
          dataIndex="icu"
          key="icu"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="配备空调地暖"
          dataIndex="aircondition"
          key="aircondition"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="电视外设"
          dataIndex="tv"
          key="tv"
          render={(value) => renderIcon(value)}
        />
        <Column
          title="床位操作"
          key="action"
          render={(_, record) => (
            <Space size="middle">
              <a
                className="iconfont icon-empty"
                onClick={() => handleDelete(record.id)}
              ></a>
              <a
                className="iconfont icon-xiugai"
                onClick={() => handleEdit(record)}
              ></a>
            </Space>
          )}
        />
      </Table>

      <Pagination
        total={total}
        current={currentPage}
        pageSize={pageSize}
        onChange={onChange}
        showSizeChanger
        showQuickJumper
        position={["bottomLeft"]}
        showTotal={(total) => `共 ${total} 条`}
      />

      <Modal
        title="确认删除"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        确认删除当前数据吗？
      </Modal>

      <Modal
        title="床位管理"
        open={isManageModalOpen}
        onOk={handleManageOk}
        onCancel={handleManageCancel}
        maskClosable={true} // 允许点击遮罩层关闭对话框
        footer={null}
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          onFinish={(values) => {
            console.log("Received values of form: ", values);

            setIsManageModalOpen(false);
          }}
        >
          <Form.Item label="床位编号" name="bednumber">
            <Input disabled />
          </Form.Item>
          <Form.Item label="所属科室" name="department">
            <Select>
              {departments.map((dept) => (
                <Select.Option key={dept.value} value={dept.value}>
                  {dept.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="氧气罐" name="oxygen">
            <Radio.Group>
              <Radio value={1}> 是 </Radio>
              <Radio value={0}> 否 </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="心电机" name="heart">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="呼吸机" name="breath">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="急救设施" name="icu">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="空调地暖" name="aircondition">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="电视外设" name="tv">
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="责任护士" name="nurse">
            <Select>
              {nurses.map((nurse) => (
                <Select.Option key={nurse.value} value={nurse.value}>
                  {nurse.label}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>

        <Space
          style={{ display: "flex", justifyContent: "center", marginTop: 16 }}
        >
          <Button type="primary" onClick={handleManageOk}>
            确认编辑
          </Button>
        </Space>
      </Modal>
    </div>
  );
}

export default BedList;
